package controllers

import (
	"encoding/json"
	"time"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/services"
	"weiboxs.com/new_h_glasses/utils"
)

type RetailController struct {
	BaseController
}

func (c *RetailController) Prepare() {
	c.BaseController.Prepare()
}

func (c *RetailController) Index() {

	c.checkAuthor("retail/index")
	c.Data["activeSidebarUrl"] = "/retail/index"

	c.display("", "retail/index_footerjs.html")
}

func (c *RetailController) DataGrid() {
	//c.checkAuthor("retail/index")
	var params models.RetailsQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &params)
	params.Depid = c.curUser.DepartmentId
	data, total := models.RetailsPageList(&params)
	c.jsonDataTable(total, data)
}

//获取配置信息
func (c *RetailController) getOption() (o map[string]interface{}) {

	o = make(map[string]interface{})

	f := models.OptionsQueryParam{}
	f.Status = "1"
	f.Depid = c.curUser.DepartmentId
	//获取医生
	f.Typeid = "10"
	o["doctor"] = models.OptionsList(&f)

	//获取验光师
	f.Typeid = "11"
	o["optometrist"] = models.OptionsList(&f)

	//营业员
	f.Typeid = "20"
	o["business"] = models.OptionsList(&f)

	return
}

//获取验光单
func (c *RetailController) Optometry() {
	c.checkAuthor("retail/index")
	archives_id, _ := c.GetInt64("archives_id")
	var params models.OptometryQueryParam
	params.Deps = c.curUser.ExtendDepartmentList
	params.ArchivesId = archives_id
	params.Limit = 2
	data, _ := models.OptometryPageList(&params)
	for k, _ := range data {
		data[k].ChufangData = models.GetOptometryDataList(data[k].Id)
	}
	c.jsonResult(enums.JRCodeSucc, "ok", data)
}

//更多验光
func (c *RetailController) OptometryMore() {
	c.checkAuthor("retail/index")
	archives_id, _ := c.GetInt64("archives_id")
	if archives_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {
		currentOptpmtryId := c.GetString("currentOptpmtryId")

		var params models.OptometryQueryParam
		params.Deps = c.curUser.ExtendDepartmentList
		params.ArchivesId = archives_id
		params.OptNotId = currentOptpmtryId

		data, count := models.OptometryPageList(&params)
		for k, _ := range data {
			data[k].ChufangData = models.GetOptometryDataList(data[k].Id)
		}
		c.jsonDataTable(count, data)
	}
	c.Data["archives_id"] = archives_id

	c.display("", "retail/optometrymore_footerjs.html", "shared/layout_dialog.html")
}

//选择库存商品
func (c *RetailController) InventoryList() {

	if c.Ctx.Input.IsPost() {

	}
	c.display("", "retail/inventorylist_footerjs.html", "shared/layout_dialog.html")
}

//添加零售
func (c *RetailController) Add() {
	c.checkAuthor("retail/add")
	c.Data["activeSidebarUrl"] = "/retail/add"

	config := c.getOption()
	c.Data["c"] = config

	c.display("retail/add.html", "retail/add_footerjs.html")
}

//选择档案时写入临时销售数据
func (c *RetailController) AddSales() {
	c.checkAuthor("retail/add")

	address_name := c.GetString("address_name")
	associator_id, _ := c.GetInt64("associator_id")
	chufang := c.GetString("chufang")
	doctor := c.GetString("doctor")
	optometrist := c.GetString("optometrist")
	goods_data := c.GetString("goods_data")
	serve_data := c.GetString("serve_data")
	hope_pick_up_time := c.GetString("hope_pick_up_time")
	pick_up_type, _ := c.GetInt("pick_up_type")
	preferential_total_price, _ := c.GetFloat("preferential_total_price")
	remark := c.GetString("remark")
	optremark := c.GetString("optremark")
	sale_person := c.GetString("sale_person")
	sell_total_price, _ := c.GetFloat("sell_total_price")
	total_real_price, _ := c.GetFloat("total_real_price")
	sales_id, _ := c.GetInt64("sales_id")

	ret := new(services.SerRetail)
	ret.Chufang = chufang
	ret.AddressName = address_name
	ret.AssociatorId = associator_id
	ret.Doctor = doctor
	ret.Optometrist = optometrist
	ret.GoodsData = goods_data
	ret.ServeData = serve_data
	ret.HopePickUpTime = hope_pick_up_time
	ret.PickUpType = pick_up_type
	ret.PreferentialTotalPrice = preferential_total_price
	ret.Remark = remark
	ret.OptRemark = optremark
	ret.SalePerson = sale_person
	ret.SellTotalPrice = sell_total_price
	ret.TotalRealPrice = total_real_price

	if sales_id > 0 { //修改
		if err := services.UpdateRetails(sales_id, &c.curUser, ret); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "ok", sales_id)
		}
	} else { //新增单据
		if ret_id, err := services.InsertRetails(&c.curUser, ret); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "ok", ret_id)
		}
	}

	c.jsonResult(enums.JRCodeFailed, "post err", "")
}

//清除临时单据
func (c *RetailController) ClearSales() {
	c.checkAuthor("retail/add")
	retail_id, _ := c.GetInt64("sales_id")
	if retail_id == 0 {
		c.jsonResult(enums.JRCodeFailed, "参数错误", "")
	}
	if err := services.ConfirmDeleteRetails(retail_id, &c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//取镜结算
func (c *RetailController) PickupPayConfirm() {
	c.checkAuthor("retail/add")
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {

	}
	c.Data["sales_id"] = sales_id;
	c.display("", "retail/pickuppayconfirm_footerjs.html", "shared/layout_dialog.html")
}

//快递发货结算
func (c *RetailController) SendoutPickupPayConfirm() {
	c.checkAuthor("retail/add")
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {

	}
	c.Data["sales_id"] = sales_id;
	c.display("", "retail/sendoutpickuppayconfirm_footerjs.html", "shared/layout_dialog.html")
}

//获取销售单明细
func (c *RetailController) QueryRetailInfo() {
	sales_id, _ := c.GetInt64("sales_id")
	if data, err := services.GetRetailsInfo(sales_id, &c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "ok", data)
	}
}

//确认支付
func (c *RetailController) PickUpPaycomfirm() {
	retail_id, _ := c.GetInt64("retail_id")
	alipay_pay_price, _ := c.GetFloat("alipay_pay_price")
	bandcard_pay_price, _ := c.GetFloat("bandcard_pay_price")
	cash_pay_price, _ := c.GetFloat("cash_pay_price")
	wechat_pay_price, _ := c.GetFloat("wechat_pay_price")
	goods_sale_list := c.GetString("goods_sale_list")

	post_company := c.GetString("PostCompany")
	post_number := c.GetString("PostNumber")
	post_user := c.GetString("PostUser")
	post_money, _ := c.GetFloat("PostMoney")
	address_name := c.GetString("AddressName")
	post_paytype, _ := c.GetInt("PostPaytype")
	post_mobile := c.GetString("PostMobile")

	data := new(services.PickUpPaycomfirmData)
	data.RetailsId = retail_id
	data.CashMoney = cash_pay_price
	data.AlipayMoney = alipay_pay_price
	data.CardMoney = bandcard_pay_price
	data.WechatMoney = wechat_pay_price

	data.PostCompany = post_company
	data.PostMobile = post_company
	data.PostMoney = post_money
	data.PostNumber = post_number
	data.AddressName = address_name
	data.PostMobile = post_mobile
	data.PostUser = post_user
	data.PostPaytype = post_paytype

	pro_d := make([]*services.PickUpPaycomfirmProduct, 0)
	json.Unmarshal([]byte(goods_sale_list), &pro_d)
	data.Products = pro_d

	if err := services.PickUpPaycomfirm(data, &c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "ok", "")
	}

}

//销售退货单
func (c *RetailController) Refund() {
	c.checkAuthor("retail/refund")
	if c.Ctx.Input.IsPost() { //保存零售信息
		//c.saveSales()
	}
	c.Data["activeSidebarUrl"] = "/retail/refund"

	c.display("", "retail/refund_footerjs.html")
}

//确认退款
func (c *RetailController) RefundConfirm() {
	c.checkAuthor("retail/refund")
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() { //保存零售信息
		//c.saveSales()
	}
	c.Data["activeSidebarUrl"] = "/retail/refund"
	c.Data["sales_id"] = sales_id

	c.display("", "retail/refundconfirm_footerjs.html")
}

//保存退货
func (c *RetailController) SaveConfirmRefund() {
	c.checkAuthor("retail/refund")

	refund_data := new(services.RefundData)
	if err := c.ParseForm(refund_data); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取出错"+err.Error(), "")
	}
	goods_list := c.GetString("goods_list")
	if err := json.Unmarshal([]byte(goods_list), &refund_data.Products); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取出错"+err.Error(), "")
	}
	if err := services.SaveConfirmRefund(refund_data, &c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, "退货出错"+err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//退货查询
func (c *RetailController) RefundQuery() {
	c.checkAuthor("retail/refund_query")

	if c.Ctx.Input.IsPost() {
		var params models.RefundsQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.Depid = c.curUser.DepartmentId
		data, total := models.RefundsPageList(&params)
		c.jsonDataTable(total, data)
	}

	c.Data["activeSidebarUrl"] = "/retail/refund_query"
	c.display("", "retail/refundquery_footerjs.html")
}

//退货清单
func (c *RetailController) RefundView() {
	c.checkAuthor("retail/refund_query")

	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {
		sales_id, _ := c.GetInt64("sales_id")
		if data, err := services.GetRefundsInfo(sales_id, &c.curUser); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "ok", data)
		}
	}
	c.Data["sales_id"] = sales_id
	c.display("", "retail/refundview_footerjs.html", "shared/layout_dialog.html")
}

//查看消费
func (c *RetailController) View() {
	c.checkAuthor("retail/add")
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	c.Data["sales_id"] = sales_id;
	c.display("", "retail/view_footerjs.html", "shared/layout_dialog.html")
}

//返回单条打印详细数据
func (c *RetailController) Printer() {
	id, err := c.GetInt64(":id")
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, "参数错误", "")
	}

	if detail, err := models.QueryRetailsDetails(id); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	} else { //打印时发送微信推送

		//微信推送
		//ser := services.WechatTemplateMessageService{Archives: detail.Archives, Host: c.Ctx.Input.Site()}
		//go ser.SendRetailsMessage(detail)

		c.jsonResult(enums.JRCodeSucc, "", detail)
	}
}

//下载销售数据
func (c *RetailController) DownloadExcelRetails() {

	c.checkAuthor("retail/index")

	gsd := c.GetString("start_date")
	ged := c.GetString("end_date")
	if len(gsd) <= 0 || len(ged) <= 0 {
		c.jsonResult(enums.JRCodeFailed, "开始与结束时间必须填写", "")
	}

	startdate := utils.GetDateParse(gsd)
	enddate := utils.GetDateParse(ged)

	if url, err := services.RetailsCreateExcel(c.curUser, startdate, enddate); err != nil {
		c.jsonResult(enums.JRCodeFailed, "表格生成失败", "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "", url)
	}

	c.jsonResult(enums.JRCodeFailed, "表格生成失败", "")
}

//取镜
func (c *RetailController) Extract() {
	c.checkAuthor("retail/extract")
	c.Data["activeSidebarUrl"] = "/retail/extract"
	c.display("", "retail/extract_footerjs.html")
}

//取镜记录
func (c *RetailController) Pickup() {
	c.checkAuthor("retail/pickup")
	c.Data["activeSidebarUrl"] = "/retail/pickup"
	c.display("", "retail/pickup_footerjs.html")
}

//取镜明细
func (c *RetailController) PickUpGoodsList() {
	c.checkAuthor("retail/pickup")
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.pageError("参数错误")
	}
	if c.Ctx.Input.IsPost() {
		var params models.RetailsDataQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.RetailsId = sales_id
		params.RelatedSel = []interface{}{"Products", "Inventory", "Snd", "Retails"}
		data, total := models.RetailsDataList(&params)
		c.jsonDataTable(total, data)
	}

	c.display("", "retail/pickupgoodslist_footerjs.html", "shared/layout_dialog.html")
}

//今日营业情况
func (c *RetailController) DailyReport() {
	c.checkAuthor("retail/dailyreport")

	startDate := utils.GetDate(time.Now().Unix())
	endDate := startDate
	if c.Ctx.Input.IsPost() {
		data, _ := services.RetailsStatistics(c.curUser, utils.GetDateParse(startDate), utils.GetDateParse(endDate))
		c.jsonResult(enums.JRCodeSucc, "ok", data)
	}
	c.Data["activeSidebarUrl"] = "/retail/dailyreport"
	c.Data["startDate"] = startDate
	c.Data["endDate"] = endDate

	c.display("", "retail/dailyreport_footerjs.html")
}

//商品定制
func (c *RetailController) Custom() {

	if c.Ctx.Input.IsPost() {
		var params models.ErpProductsQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.Depids = c.curUser.ExtendDepartmentList
		data, total := models.ErpProductsPageList(&params)
		c.jsonDataTable(total, data)
	}
	c.display("", "retail/custom_footerjs.html", "shared/layout_dialog.html")
}

//商品定制
func (c *RetailController) CustomSave() {
	product_id, _ := c.GetInt64("product_id")

	if c.Ctx.Input.IsPost() {
		eye_data := c.GetString("eye_data")
		if invs, err := services.ConfirmRetailsCustom(product_id, eye_data, &c.curUser); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		} else {
			c.jsonResult(enums.JRCodeSucc, "ok", invs)
		}
	}

	product, _ := models.GetErpProductsById(product_id, &c.curUser)
	c.Data["product"] = product
	c.display("", "retail/customsave_footerjs.html", "shared/layout_dialog.html")
}

//历史销售商品
func (c *RetailController) History() {
	if c.Ctx.Input.IsPost() {
		var params models.RetailsDataQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.Deps = c.curUser.ExtendDepartmentList
		params.RelatedSel = []interface{}{"Products", "Inventory", "Snd", "Retails"}
		data, total := models.RetailsDataList(&params)

		//获取价格
		paramsPrice := new(models.InventoryPriceQueryParams)
		for k, _ := range data {
			paramsPrice.DepId = data[k].Inventory.DepartmentId
			paramsPrice.Snd = data[k].Snd
			paramsPrice.Product = data[k].Products
			paramsPrice.Sph = data[k].Snd.Sph
			paramsPrice.Cyl = data[k].Snd.Cyl
			paramsPrice.Add = data[k].Snd.Add
			price := models.GetInventoryPriceForQueryParams(paramsPrice);
			if price.Id > 0 {
				data[k].Inventory.SuggestedPrice = price.SuggestedPrice
			}
		}
		c.jsonDataTable(total, data)
	}
	c.display("", "retail/history_footerjs.html", "shared/layout_dialog.html")
}

//订单作废
func (c *RetailController) Discard() {
	sales_id, _ := c.GetInt64("sales_id")
	if sales_id == 0 {
		c.jsonResult(enums.JRCodeFailed, "参数错误", "")
	}
	if err := services.RetailDiscard(sales_id); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "ok", "")
	}
}
